package bsts.util.validation;

import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TelephoneValidation extends InputVerifier implements ActionListener {
	
	@Override
	public boolean verify(JComponent input) {
		String regex = "[6|8-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]";
		String testText = "";
		
		Pattern p = Pattern.compile(regex);

		JTextField myTextField = (JTextField) input;
        
		testText = myTextField.getText();
		
		Matcher m = p.matcher(testText);
        
		if (m.matches()){
			return true;
		}else{ 
			return false;
		}

	}
		
	public boolean shouldYieldFocus(JComponent input) {
        boolean inputOK = verify(input);
        String strError = "";

        if (inputOK) {
            return true;
        }


        //Pop up the message dialog.
        strError += "\nPlease a valid Telephone No.";
        JOptionPane.showMessageDialog(null, //no owner frame
                                      strError, //text to display
                                      "Invalid Telephone No.", //title
                                      JOptionPane.WARNING_MESSAGE);

        //Reinstall the input verifier. 
        input.setInputVerifier(this);

        //Beep and then tell whoever called us that we don't
        //want to giveup focus.
        Toolkit.getDefaultToolkit().beep();
        return false;
    }

	@Override
	public void actionPerformed(ActionEvent e) {
		JTextField source = (JTextField)e.getSource();
		shouldYieldFocus(source); //ignore return value
        source.selectAll();	
	}


}
